package heap.hard;

import java.util.Arrays;
import java.util.PriorityQueue;

public class CourseScheduleIII_630 {

    public int scheduleCourse(int[][] courses) {
        PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> b - a);
        Arrays.sort(courses, (a, b) -> a[1] - b[1]);
        int sum = 0;
        for (int[] cours : courses) {
            queue.offer(cours[0]);
            sum += cours[0];
            if (sum > cours[1]) {
                sum -= queue.poll();
            }
        }
        return queue.size();
    }
}
